<template>
  <div class="addExpense">
    <el-form
      ref="form"
      :model="form"
      :rules="roleCodeRule"
      label-width="120px"
    >
      <el-row>
        <mainTilte title="基本信息" />
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="商品分类">
            <!-- <el-cascader
              ref="cascader"
              v-model="form.category_id"
              :options="classifyList"
              @change="handleChangeClassify"
              :props="propsClassify"
              :clearable="true"
            ></el-cascader> -->
            <el-input
              v-model.trim="cateName"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            label="配件编码"
            prop="code"
          >
            <el-input
              v-model.trim="form.code"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            label="配件名称"
            prop="name_ch"
          >
            <el-input
              v-model.trim="form.name_ch"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="配件流向">
            <el-select
              v-model.trim="form.flow_to"
              placeholder="配件流向"
              disabled
              clearable
            >
              <el-option
                v-for="(item, index) of flwList"
                :key="index"
                :label="item.name"
                :value="item.code"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="8">
          <el-form-item label="所属供应商">
            <el-autocomplete v-model="form.supplier_name" :fetch-suggestions="queryBlnoAsyncSuppier" placeholder="请输入内容" disabled clearable @select="handleSelectSuppier" />
          </el-form-item>
        </el-col> -->
        <el-col :span="8">
          <el-form-item label="采购员">
            <el-autocomplete
              v-model="form.purchase_name"
              :fetch-suggestions="queryBlnoAsync"
              placeholder="请输入内容"
              disabled
              clearable
              @select="handleSelectBlno"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="配件主图">
            <el-image
              v-if="form.image_url"
              :src="form.image_url"
              style="width: 120px;height: 120px;"
              fit="cover"
              :preview-src-list="[ form.image_url ]"
            />
            <i
              v-else
              class="el-icon-plus avatar-uploader-icon"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <mainTilte title="包装信息" />
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="邮购包装尺寸">
            <div class="sizeStyle">
              <div>
                <el-input
                  v-model="form.length"
                  placeholder="长"
                  disabled
                >
                  <template slot="append">CM</template>
                </el-input>
              </div>
              <div style="margin-left: 8px">
                <el-input
                  v-model="form.width"
                  placeholder="宽"
                  disabled
                >
                  <template slot="append">CM</template>
                </el-input>
              </div>
              <div style="margin-left: 8px">
                <el-input
                  v-model="form.height"
                  placeholder="高"
                  disabled
                >
                  <template slot="append">CM</template>
                </el-input>
              </div>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="体积(公制)">
            <el-input
              v-model.trim="form.volume"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="邮购包装尺寸(美制)">
            <div class="sizeStyle">
              <div>
                <el-form-item
                  label=""
                  prop="length"
                >
                  <el-input
                    v-model="form.length_AS"
                    placeholder="长"
                    disabled
                  >
                    <template slot="append">英寸</template>
                  </el-input>
                </el-form-item>
              </div>
              <div style="margin-left: 8px">
                <el-form-item
                  label=""
                  prop="width"
                >
                  <el-input
                    v-model="form.width_AS"
                    placeholder="宽"
                    disabled
                  >
                    <template slot="append">英寸</template>
                  </el-input>
                </el-form-item>
              </div>
              <div style="margin-left: 8px">
                <el-form-item
                  label=""
                  prop="height"
                >
                  <el-input
                    v-model="form.height_AS"
                    placeholder="高"
                    disabled
                  >
                    <template slot="append">英寸</template>
                  </el-input>
                </el-form-item>
              </div>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            label="毛重（美制）"
            prop="weight_gross_AS"
          >
            <el-input
              v-model="form.weight_gross_AS"
              placeholder="请输入内容"
              disabled
            >
              <template slot="append">lbs</template>
            </el-input>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="8">
          <el-form-item label="重量">
            <el-input v-model="form.weight" placeholder="请输入内容" disabled>
              <template slot="append">kg</template>
            </el-input>
          </el-form-item>
        </el-col> -->
        <!-- <el-col :span="8">
          <el-form-item label="外箱包装尺寸">
            <div class="sizeStyle">
              <div>
                <el-input v-model="form.length_outside" placeholder="长" disabled>
                  <template slot="append">CM</template>
                </el-input>
              </div>
              <div style="margin-left: 8px">
                <el-input v-model="form.width_outside" placeholder="宽" disabled>
                  <template slot="append">CM</template>
                </el-input>
              </div>
              <div style="margin-left: 8px">
                <el-input v-model="form.height_outside" placeholder="高" disabled>
                  <template slot="append">CM</template>
                </el-input>
              </div>
            </div>
          </el-form-item>
        </el-col> -->
        <!-- <el-col :span="8">
          <el-form-item label="体积">
            <el-input v-model.trim="form.volume_outside" disabled />
          </el-form-item>
        </el-col> -->
        <el-col :span="8">
          <el-form-item label="外箱箱率">
            <el-input
              v-model.trim="form.box_rate"
              disabled
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <mainTilte title="适用SKU" />
      </el-row>
      <el-row>
        <egrid
          v-loading="loading"
          class="egrid"
          stripe
          fit
          border
          highlight-current-row
          element-loading-text="正在努力加载中..."
          :column-type="['selection']"
          :data="tableData"
          :columns="columns"
          :columns-schema="columnsSchema"
          :columns-handler="columnsHandler"
          @selection-change="checkIds"
        />
      </el-row>
      <div class="dialog-footer-center">
        <span>
          <el-button
            type="primary"
            @click="$router.go(-1)"
          >返回</el-button>
        </span>
      </div>
    </el-form>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import list from '@/layout/mixin/list'
import thund from '@/components/base/thund'
import dicValues from '@/components/dicTransform/index'
export default {
  mixins: [list],
  data() {
    const DICTIONARIES = {
      auditStatus: [
        // 商品所属客户类型 0-内部员工 1-客户商品
        {
          code: 0,
          name: '内部员工'
        },
        {
          code: 1,
          name: '客户商品'
        }
      ],
      // 包装方式 ：1-普通商品 2-多箱包装
      splitOrder: [
        {
          code: 1,
          name: '普通商品'
        },
        {
          code: 2,
          name: '多箱包装'
        }
      ]
    }
    return {
      loading: false,
      form: {
        code: '',
        category_id: '',
        image_url: '',
        name_ch: '',
        flow_to: '',
        purchase_name: '',
        purchase_id: '',
        length: '',
        width: '',
        height: '',
        volume: '',
        weight: '',
        length_outside: '',
        width_outside: '',
        height_outside: '',
        volume_outside: '',
        box_rate: '',
        product_id: '',

        supplier_name: ''
      },
      roleCodeRule: {},
      freightList: [],
      columns: [
        {
          label: '缩略图',
          prop: 'image_url',
          width: '200',
          align: 'center',
          tooltip: false
        },
        {
          label: '系统sku',
          prop: 'code',
          align: 'center',
          tooltip: false
        },
        {
          label: '中文名称',
          prop: 'name_ch',
          width: '200',
          align: 'center',
          tooltip: false
        },
        {
          label: '英文名称',
          prop: 'name_en',
          align: 'center',
          tooltip: false
        },
        {
          label: '包装方式',
          prop: 'packing_method',
          width: '200',
          align: 'center',
          tooltip: false
        },
        {
          label: '商品分类',
          prop: 'category_text',
          width: '200',
          align: 'center',
          tooltip: false
        }
      ],
      columnsSchema: {
        缩略图: {
          propsHandler({ col, row }) {
            return {
              img: row.image_url
            }
          },
          component: thund
        },
        包装方式: {
          propsHandler({ col, row }) {
            return {
              dictionaries: DICTIONARIES['splitOrder'],
              code: row[col.prop]
            }
          },
          component: dicValues
        }
      },
      fileList: [],
      dialogAddProductVisible: false,
      checkChildList: [],
      classifyList: [],
      propsClassify: {
        disabled: 'disabled' // 商品分类只能选择二级
      },
      // 配件流向 流向 1-国内 2-国外
      flwList: [
        {
          name: '国内',
          code: 1
        },
        {
          name: '国外',
          code: 2
        }
      ],
      imageAction: process.env.VUE_APP_BASE_API + '/upload/image',
      headers: {
        authorization: ''
      },
      tableData: [],
      isEdit: false,
      cateName: ''
    }
  },
  computed: {
    ...mapGetters(['name', 'avatar', 'roles', 'email', 'token', 'user_id']),
    volume() {
      return this.form.length * this.form.width * this.form.height
    },
    volume_outside() {
      return (
        this.form.length_outside *
        this.form.width_outside *
        this.form.height_outside
      )
    }
  },
  created() {
    this.getUser()
  },
  mounted() {
    this.getTreeList()
    this.editList()
  },
  methods: {
    editList() {
      if (this.$route.query && this.$route.query.id) {
        this.isEdit = true
        this.getDatailData(this.$route.query.id)
      }
    },
    getDatailData(id) {
      this.$http
        .get(`/parts/${id}`)
        .then((res) => {
          if (res.code === 10000) {
            this.form = res.data
            this.form.list = res.data.list.map((e) => {
              e['category_text'] = `${e.parent_name}-${e.category_name}`
              return e
            })
            let isBase
            if (this.form.image_url) {
              isBase = this.form.image_url.indexOf(process.env.VUE_APP_BASE_API)
            } else {
              isBase = -2
            }
            this.form.image_url =
              isBase === -1
                ? process.env.VUE_APP_BASE_API + this.form.image_url
                : isBase === 0
                  ? this.form.image_url
                  : ''
            this.cateName = this.form.category_name
              ? this.form.category_parent_name + ',' + this.form.category_name
              : ''
            if (res.data.list && res.data.list.length > 0) {
              this.tableData = res.data.list
            }
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    // 获取商品分类
    getTreeList() {
      this.$http
        .get(`/getListTree`)
        .then((res) => {
          if (res.code === 10000 && res.data && res.data.length > 0) {
            res.data.forEach((element) => {
              element['label'] = element.name
              element['value'] = element.id
              if (element.children && element.children.length > 0) {
                element['disabled'] = false
                element.children.forEach((it) => {
                  it['label'] = it.name
                  it['value'] = it.id
                })
              } else {
                element['disabled'] = true
              }
            })
            this.classifyList = res.data
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    getUser() {
      this.user = {
        username: this.name,
        role: this.roles.join(' | '),
        email: this.email,
        avatar: this.avatar
      }
      this.headers.authorization = 'Bearer ' + this.token
    },
    handleChangeClassify(data) {
      this.form.category_id = data[1]
      this.classifyList.forEach((element) => {
        if (element.children && element.children.length > 0) {
          element.children.forEach((it) => {
            if (it.id === this.form.category_id) {
              this.form.ZH_HS = it.ZH_HS
              this.form.EN_HS = it.EN_HS
              this.form.tax_rebate_rate = it.tax_rebate_rate
              this.form.tax_tariff_rate = it.tax_tariff_rate
            }
          })
        }
      })
    },
    createStateFilter(queryString) {
      return (state) => {
        return (
          state.value.toLowerCase().indexOf(queryString.toLowerCase()) != -1
        )
      }
    },
    handleSelect() { },
    // 所属供应商查询
    queryBlnoAsyncSuppier(queryString, cb) {
      const params = {
        page: 1,
        limit: 100000000,
        audit_status: 2,
        cooperation_status: 1
      }
      this.$http
        .get(`/supply`, { params })
        .then((res) => {
          if (res.code == 10000 && res.data && res.data.length > 0) {
            const restaurants = res.data.map((item) => {
              return { value: item.name, label: item.id }
            })
            const results = queryString
              ? restaurants.filter(this.createStateFilter(queryString))
              : restaurants
            clearTimeout(this.timeout)
            this.timeoutNo = setTimeout(() => {
              cb(results)
            }, 3000 * Math.random())
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    handleSelectSuppier(data) {
      this.form.supplier_id = data.label
    },
    // 采购员
    queryBlnoAsync(queryString, cb) {
      this.$http
        .get(`/supply/buyers/list`)
        .then((res) => {
          if (res.code === 10000 && res.data && res.data.buyers.length > 0) {
            const restaurants = res.data.buyers.map((item) => {
              return { value: item }
            })
            const results = queryString
              ? restaurants.filter(this.createStateFilter(queryString))
              : restaurants
            clearTimeout(this.timeout)
            this.timeoutNo = setTimeout(() => {
              cb(results)
            }, 3000 * Math.random())
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    handleSelectBlno() { },
    // 自定义操作栏
    columnsHandler() { },
    handleImageSuccess(response, file, fileList) {
      if (response.code !== 10000) {
        this.$message.error(response.message)
      } else {
        this.form.image_url = response.data
      }
    },
    beforeImageUpload(file) {
      const image =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/jpg' ||
        file.type === 'image/gif'
      if (!image) {
        this.$message.error('只支持 jpg/jpeg/png/gif 格式!')
      }
      let isLtSize = false
      isLtSize = file.size / 1024 / 1024 < 5
      if (!isLtSize) {
        this.$message.error('最大支持 5MB!')
      }
      return image && isLtSize
    },
    beforeRemoveFile() {
      // this.fileList = [];
    },
    saveData() {
      const dataLength = this.checkChildList.length
      if (dataLength === 0) {
        this.$message.error('请至少选择一条数据')
        return false
      }
      this.checkChildList.forEach((ele) => {
        const productObj = {
          image_url: ele.image_url,
          code: ele.code,
          name_ch: ele.name_ch,
          name_en: ele.name_en,
          type: ele.type,
          category_name: ele.category_name,
          id: ele.id
        }
        this.tableData.push(productObj)
      })
      this.dialogAddProductVisible = false
    },
    checkChildIds(data) {
      this.checkChildList = data
    },

    // 保存
    onSubmit() {
      this.form.product_id =
        this.ids && this.ids.length > 0 ? this.ids.join(',') : this.ids
      this.form.volume = this.form.length * this.form.width * this.form.height
      this.form.volume_outside =
        this.form.length_outside *
        this.form.width_outside *
        this.form.height_outside
      if (this.isEdit) {
        // 编辑
        this.$http
          .put(`/parts/${this.form.id}`, this.form)
          .then((res) => {
            if (res.code === 10000) {
              this.$message.success('修改成功')
              this.$router.push('/product/accessoriesManage')
            }
          })
          .catch((err) => {
            console.log(err)
          })
      } else {
        this.$http
          .post(`/parts`, this.form)
          .then((res) => {
            if (res.code === 10000) {
              this.$message.success('新增成功')
              this.$router.push('/product/accessoriesManage')
            }
          })
          .catch((err) => {
            console.log(err)
          })
      }
    }
  }
}
</script>

<style scoped>
.addExpense {
  padding: 15px;
  background: #fff;
}
/deep/.el-select,
.el-autocomplete,
.el-cascader {
  width: 100%;
}
.sizeStyle {
  display: flex;
}
.sizeStyle /deep/ .el-input__inner {
  border-right: 0;
}
.sizeStyle /deep/ .el-input-group__append {
  padding-left: 4px;
  padding-right: 4px;
  font-size: 14px;
  color: #333333;
  background: #fff;
}
.avatar-uploader /deep/ .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader /deep/ .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>
